package com.team622.shop.user.service.interceptors;

import com.team622.shop.common.exceptions.BusinessException;
import com.team622.shop.common.exceptions.enums.Resp;
import com.team622.shop.user.service.handlers.BaseContextHandler;
import com.team622.shop.user.service.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 授权拦截器
 *
 * @author team622
 * @since 2025-07-02
 */
@Slf4j
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {
    /**
     * JWT工具类，用于解析和验证令牌
     */
    @Resource
    private JwtUtil jwtUtil;

    /**
     * 拦截器前置处理
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long tid = Thread.currentThread().getId();
        log.info("AuthorizationInterceptor preHandle id:{}", tid);
        log.info("uri:{}", request.getRequestURI());
        // 从请求头获取token
        String token = request.getHeader("Authorization");
        log.info("token:{}", token);

        // 检查令牌是否存在
        if (token == null || token.isEmpty()) {
            log.info("uri:{}", request.getRequestURI());
            throw new BusinessException(Resp.TOKEN_MISSING);
        }

        // 解析token，获取用户ID
        token = token.replace("Bearer ", "");
        Claims claims = jwtUtil.parseAccessToken(token);

        Long id = claims.get("adminId", Long.class) == null ? claims.get("memberId", Long.class) : claims.get("adminId", Long.class);
        log.info("id:{}", id);

        // 设置用户ID到线程上下文
        BaseContextHandler.set(id);
        return true;
    }
}
